# -- coding: utf-8 --
import tkinter.messagebox
import sys

sys.path.append("../MvImport")
from MvCameraControl_class import *
from CamOperation_class import *
from PIL import Image, ImageTk


# 获取选取设备信息的索引，通过[]之间的字符去解析
def TxtWrapBy(start_str, end, all):
    start = all.find(start_str)
    if start >= 0:
        start += len(start_str)
        end = all.find(end, start)
        if end >= 0:
            return all[start:end].strip()


# 将返回的错误码转换为十六进制显示
def ToHexStr(num):
    chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
    hexStr = ""
    if num < 0:
        num = num + 2 ** 32
    while num >= 16:
        digit = num % 16
        hexStr = chaDic.get(digit, str(digit)) + hexStr
        num //= 16
    hexStr = chaDic.get(num, str(num)) + hexStr
    return hexStr


if __name__ == "__main__":
    global deviceList
    deviceList = MV_CC_DEVICE_INFO_LIST()
    global tlayerType
    tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
    global cam
    cam = MvCamera()
    global nSelCamIndex
    nSelCamIndex = 0
    global obj_cam_operation
    obj_cam_operation = 0
    global b_is_run
    b_is_run = False

    # 界面设计代码
    window = tk.Tk()
    window.title('实时摄像头')
    window.geometry('1150x650')

    model_val = tk.StringVar()
    global triggercheck_val
    triggercheck_val = tk.IntVar()
    page = Frame(window, height=400, width=60, relief=GROOVE, bd=5, borderwidth=4)
    page.pack(expand=True, fill=BOTH)
    panel = Label(page)
    panel.place(x=190, y=10, height=600, width=1000)


    # 绑定下拉列表至设备信息索引
    def xFunc(event):
        global nSelCamIndex
        nSelCamIndex = TxtWrapBy("[", "]", device_list.get())


    # ch:枚举相机 | en:enum devices
    def enum_devices():
        global deviceList
        global obj_cam_operation
        deviceList = MV_CC_DEVICE_INFO_LIST()
        tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
        ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
        if ret != 0:
            tkinter.messagebox.showerror('显示错误', '枚举设备失败! ret = ' + ToHexStr(ret))
        if deviceList.nDeviceNum == 0:
            tkinter.messagebox.showinfo('显示信息', '没有发现设备!')
        print("查找%d台可用设备!" % deviceList.nDeviceNum)

        devList = []
        for i in range(0, deviceList.nDeviceNum):
            mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
            if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE:
                print("\ngige设备: [%d]" % i)
                chUserDefinedName = ""
                for per in mvcc_dev_info.SpecialInfo.stGigEInfo.chUserDefinedName:
                    if 0 == per:
                        break
                    chUserDefinedName = chUserDefinedName + chr(per)
                print("设备型号名称: %s" % chUserDefinedName)

                nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
                nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
                nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
                nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
                print("当前设备IP: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
                devList.append(
                    "[" + str(i) + "]GigE: " + chUserDefinedName + "(" + str(nip1) + "." + str(nip2) + "." + str(
                        nip3) + "." + str(nip4) + ")")
            elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
                # print("\nu3v设备: [%d]" % i)
                chUserDefinedName = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chUserDefinedName:
                    if per == 0:
                        break
                    chUserDefinedName = chUserDefinedName + chr(per)
                # print("设备型号名称: %s" % chUserDefinedName)

                strSerialNumber = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber:
                    if per == 0:
                        break
                    strSerialNumber = strSerialNumber + chr(per)
                print("客户编号: %s" % strSerialNumber)
                devList.append("[" + str(i) + "]USB: " + chUserDefinedName + "(" + str(strSerialNumber) + ")")
        device_list["value"] = devList
        device_list.current(0)

    # ch:打开相机 | en:open device
    def open_device():
        global deviceList
        global nSelCamIndex
        global obj_cam_operation
        global b_is_run
        if True == b_is_run:
            tkinter.messagebox.showinfo('显示信息', '摄像头正在运行!')
            return
        obj_cam_operation = CameraOperation(cam, deviceList, nSelCamIndex)
        ret = obj_cam_operation.Open_device()
        if 0 != ret:
            b_is_run = False
        else:
            model_val.set('continuous')
            b_is_run = True


    # ch:开始取流 | en:开始获取图像
    def start_grabbing():
        global obj_cam_operation
        obj_cam_operation.Start_grabbing(window, panel)


    # ch:停止取流 | en:停止获取图像
    def stop_grabbing():
        global obj_cam_operation
        obj_cam_operation.Stop_grabbing()

    # ch:关闭设备 | Close device
    def close_device():
        global b_is_run
        global obj_cam_operation
        obj_cam_operation.Close_device()
        b_is_run = False

    # ch:设置触发模式 | en:set trigger mode
    def set_triggermode():
        global obj_cam_operation
        strMode = model_val.get()
        obj_cam_operation.Set_trigger_mode(strMode)


    # ch:设置触发命令 | en:set trigger software
    def trigger_once():
        global triggercheck_val
        global obj_cam_operation
        nCommand = triggercheck_val.get()
        obj_cam_operation.Trigger_once(nCommand)


    # ch:保存bmp图片 | en:save bmp image
    def bmp_save():
        global obj_cam_operation
        obj_cam_operation.b_save_bmp = True


    # ch:保存jpg图片 | en:save jpg image
    def jpg_save():
        global obj_cam_operation
        obj_cam_operation.b_save_jpg = True

    # 窗口组件
    xVariable = tkinter.StringVar()
    device_list = ttk.Combobox(window, textvariable=xVariable, width=33)
    device_list.place(x=20, y=50)
    device_list.bind("<<ComboboxSelected>>", xFunc)

    btn_enum_devices = tk.Button(window, text='获取USB设备', width=35, height=1, bg="#ffffe6", command=enum_devices)
    btn_enum_devices.place(x=20, y=100)
    btn_open_device = tk.Button(window, text='打开设备', width=15, height=1, bg="#cbfcf2", command=open_device)
    btn_open_device.place(x=20, y=185)
    btn_close_device = tk.Button(window, text='关闭设备', width=15, height=1, bg="#cbfcf2", command=close_device)
    btn_close_device.place(x=160, y=185)

    radio_continuous = tk.Radiobutton(window, text='连续不断的', variable=model_val, value='continuous', width=15,
                                      height=1, command=set_triggermode)
    radio_continuous.place(x=20, y=240)
    radio_trigger = tk.Radiobutton(window, text='触发模式', variable=model_val, value='triggermode', width=15,
                                   height=1, command=set_triggermode)
    radio_trigger.place(x=160, y=240)
    model_val.set(1)

    btn_start_grabbing = tk.Button(window, text='开始抓取', width=15, height=1, bg="#effffd", command=start_grabbing)
    btn_start_grabbing.place(x=20, y=330)
    btn_stop_grabbing = tk.Button(window, text='停止抓取', width=15, height=1, bg="#effffd", command=stop_grabbing)
    btn_stop_grabbing.place(x=160, y=330)

    btn_save_bmp = tk.Button(window, text='保存为BMP', width=15, height=1, bg="#dedbff", command=bmp_save)
    btn_save_bmp.place(x=20, y=400)
    btn_save_jpg = tk.Button(window, text='保存为JPG', width=15, height=1, bg="#dedbff", command=jpg_save)
    btn_save_jpg.place(x=160, y=400)

    window.mainloop()
